<?php

/**
 * This is the model class for table "{{category}}".
 *
 * The followings are the available columns in table '{{category}}':
 * @property string $cate_id
 * @property integer $cate_pid
 * @property string $cate_name
 * @property integer $cate_type
 * @property integer $cate_contype 
 * @property string $cate_link
 * @property integer $cate_order
 * @property integer $cate_recommend
 * @property string $cate_des
 */
class Category extends CActiveRecord
{
	public $deep;
	
	const CATEGORY_NEWS = 1;	//此分类为新闻类目录
	const CATEGORY_MEDIA = 3;	//此分类为产品类目录
	const CATEGORY_CUSTOMER = 2;	//此分类是客户中心目录
	const CATEGORY_ABOUT = 4;	//此分类为关于我们目录
    
    const CATEGORY_LAB = 5;     //此分类为实验室目录
	
	//为了完成学校网站而增加的分类
	const CATEGORY_BASEINFO = 5;	//此分类为学校概况
	const CATEGORY_TEACHER = 6;		//此分类为在名师风采
	const CATEGORY_DEYUE = 7;		//此分类为德育工作
	const CATEGORY_JIAOWU = 8;		//此分类为教务工作
	const CATEGORY_PARTY = 9;		//此分类为党政建设
	const CATEGORY_STUDENTS = 10;	//此分类为学生之家
	const CATEGORY_PARENTS = 11;	//此分类为家校互动 

	/**页面类型*/
	const CONTENT_EMPTY = 0;	//未设置页面类型
	const CONTENT_STORY = 1;	//分类汇集类型
	const CONTENT_PAGE = 2;		//单页类
	const CONTENT_GALLERY = 3;	//图集类
	const CONTENT_FILE = 4;		//此分类为文件类
	const CONTENT_AUDIO = 5;	//此分类为音频类
	const CONTENT_VIDEO = 6;	//此分类为视频类
	
// 	以下为完成学校网站模板而进行的修改
// 	const CONTENT_GALLERY_LIST = 7;	//此分类为图集列表页面类型
// 	const CONTENT_FILE_LIST = 8;	//此分类为文件列表页面类型
// 	const CONTENT_AUDIO_LIST = 9;	//此分类 为音频列表页面类型
// 	const CONTENT_VIDEO_LIST = 10;	//此分类为视频列表页面类型
	
	const CATEGORY_RECOMMEND_SITE = 1;	//推荐到首页
	const CATEGORY_RECOMMEND_CHANNELS = 2;	//推荐到频道
	const CATEGORY_RECOMMEND_CANCEL = 0;	//取消推荐
	/**
	 * Returns the static model of the specified AR class.
	 * @return Category the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{category}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('cate_name, cate_pid, cate_type, cate_contype, cate_recommend', 'required'),
			array('cate_pid, cate_order, cate_recommend', 'numerical', 'integerOnly'=>true),
			array('cate_name', 'length', 'max'=>50),
			array('cate_type', 'length', 'max'=>30),
			array('cate_link', 'url'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('cate_id, cate_pid, cate_name, cate_type, cate_order, cate_recommend, cate_des', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'media' => array(self::HAS_MANY, 'Media', 'media_cid','condition'=>'media.media_status ='.Media::STATUS_PUBLISHED,'order'=>'media.media_id DESC'),
			'product' => array(self::HAS_MANY, 'Product', 'pro_cid'),
			'project'=>array(self::HAS_MANY, 'Project', 'pro_cid'),
			'news' => array(self::HAS_MANY, 'Article', 'arc_cid'),
			'children' => array(self::HAS_MANY, 'Category', 'cate_pid'),
			'parent' => array(self::BELONGS_TO, 'Category', 'cate_id')
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'cate_id' => Yii::t('category','Id'),
			'cate_pid' => Yii::t('category','Parent'),
			'cate_name' => Yii::t('category','Name'),
			'cate_type' => Yii::t('category','Type'),
			'cate_contype' => Yii::t('category','Content Type'),
			'cate_link' => Yii::t('category','Link'),
			'cate_order' => Yii::t('category','Order'),
			'cate_recommend' => Yii::t('category','Recommend'),
			'cate_des' => Yii::t('category','Description'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('cate_id',$this->cate_id,true);
		$criteria->compare('cate_pid',$this->cate_pid);
		$criteria->compare('cate_name',$this->cate_name,true);
		$criteria->compare('cate_type',$this->cate_type,true);
		$criteria->compare('cate_order',$this->cate_order);
		$criteria->compare('cate_recommend',$this->cate_recommend);
		$criteria->compare('cate_des',$this->cate_des,true);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}

	public static function getChildrenObject($array,$pid=0,$y=0,&$tdata=array())
	{
		foreach ($array as $value)
		{
			if($value->cate_pid == $pid)
			{
				$n = $y + 1;
				$value->deep = $n;
				if($n > 1)
				{
					$value->cate_name = $value->cate_name;					
				}
				$tdata[]=$value;
				self::getChildrenObject($array,$value->cate_id,$n,$tdata);//这里递归调用，不明白递归的朋友，去找几个简单的递归例子熟悉下
				
			}
		}
		return $tdata;
	}
	public function getChildrenArray($array,$pid=0,$y=0,&$tdata=array())
	{
		//然后递归的取出各个子分类，这里默认的$pid=0是因为数据库中的pid为0的表示是第一级分类
		foreach ($array as $value)
		{
			if($value['cate_pid']==$pid){
				$n = $y + 1;
				$value['deep'] = $n;
				if($n > 1)
				{
					$value['cate_name']=$value['cate_name'];
				}
				$tdata[]=$value;
				$this->getChildrenArray($array,$value['cate_id'],$n,$tdata);//这里递归调用，不明白递归的朋友，去找几个简单的递归例子熟悉下
			}
		}
		return $tdata;
	}

	public function getCategoryList($array,$pid=0,$y=0,&$tdata=array())
	{
		//然后递归的取出各个子分类，这里默认的$pid=0是因为数据库中的pid为0的表示是第一级分类
		foreach ($array as $value)
		{
			if($value['cate_pid']==$pid){
				$n = $y + 1;
				$value['deep'] = $n;
				if($n > 1)
				{
					$nbsp = '|';
					for($i = 1; $i < $n; $i++)
					{
						$nbsp .= "－";
					}
					$value['cate_name']=$nbsp.$value['cate_name'].'['.$value['cate_contype'].']';
				}
				$tdata[]=$value;
				$this->getCategoryList($array,$value['cate_id'],$n,$tdata);//这里递归调用，不明白递归的朋友，去找几个简单的递归例子熟悉下
			}
		}
		return $tdata;
	}
	
	public function getCategoryModuleId($id)
	{
			switch ($id) {
			case self::CATEGORY_NEWS:
			 	return 'News';
				break;
			case self::CATEGORY_MEDIA:
				return 'Photos';
				break;
			case self::CATEGORY_CUSTOMER:
				return 'Customer Service';
				break;
			case self::CATEGORY_ABOUT:
				return 'About Us';
				break;
            case self::CATEGORY_LAB:
                return 'Labs';
                break;

		}		
	}
	
	public function getCategoryType($id)
	{
		switch ($id) {
			case self::CATEGORY_NEWS:
			 	return Yii::t('category','Article');
				break;
			case self::CATEGORY_MEDIA:
				return Yii::t('category','Media');
				break;
			case self::CATEGORY_CUSTOMER:
				return Yii::t('category', 'Customer Service');
				break;
			case self::CATEGORY_ABOUT:
				return Yii::t('category', 'About Us');
				break;
            case self::CATEGORY_LAB:
                return Yii::t('category','Labs');
                break;
		}
	}
	
	public function generateCategoryDropdownListArray()
	{
		return array(
			self::CATEGORY_NEWS => self::getCategoryType(self::CATEGORY_NEWS),
			self::CATEGORY_MEDIA => self::getCategoryType(self::CATEGORY_MEDIA),
			self::CATEGORY_CUSTOMER => self::getCategoryType(self::CATEGORY_CUSTOMER),
			self::CATEGORY_ABOUT=>self::getCategoryType(self::CATEGORY_ABOUT),
            self::CATEGORY_LAB=>self::getCategoryType(self::CATEGORY_LAB)
		);
	}

	public function getContentType($type)
	{
		switch ($type) {
			case self::CONTENT_AUDIO:
			 	return Yii::t('category','AUDIO');
				break;
			case self::CONTENT_FILE:
				return Yii::t('category','FILE');
				break;
			case self::CONTENT_GALLERY:
				return Yii::t('category','GALLERY');
				break;
			case self::CONTENT_PAGE:
				return Yii::t('category','PAGE');
				break;
			case self::CONTENT_STORY:
				return Yii::t('category','STORY');
				break;
			case self::CONTENT_VIDEO:
				return Yii::t('category','VIDEO');
				break;
				
			//以下内容为完成学校主题模板面增加
// 			case self::CONTENT_AUDIO_LIST:
// 				return Yii::t('category', 'AUDIO_LIST');
// 				break;
// 			case self::CONTENT_FILE_LIST:
// 				return Yii::t('category','FILE_LIST');
// 				break;
// 			case self::CONTENT_GALLERY_LIST:
// 				return Yii::t('category','GALLERY_LIST');
// 				break;
// 			case self::CONTENT_VIDEO_LIST:
// 				return Yii::t('category','VIDEO_LIST');
// 				break;
			default:
				return Yii::t('category','EMPTY');
				break;
		}
	}
	
	public function generateContentTypeDropdownListArray()
	{
		return array(
			self::CONTENT_EMPTY=>self::getContentType(self::CONTENT_EMPTY),
			self::CONTENT_STORY => self::getContentType(self::CONTENT_STORY),
			self::CONTENT_PAGE => self::getContentType(self::CONTENT_PAGE),
			self::CONTENT_AUDIO => self::getContentType(self::CONTENT_AUDIO),
// 			self::CONTENT_AUDIO_LIST=>self::getContentType(self::CONTENT_AUDIO_LIST),
			self::CONTENT_FILE => self::getContentType(self::CONTENT_FILE),
// 			self::CONTENT_FILE_LIST=>self::getContentType(self::CONTENT_FILE_LIST),
			self::CONTENT_GALLERY => self::getContentType(self::CONTENT_GALLERY),
// 			self::CONTENT_GALLERY_LIST=>self::getContentType(self::CONTENT_GALLERY_LIST),
			self::CONTENT_VIDEO => self::getContentType(self::CONTENT_VIDEO),
// 			self::CONTENT_VIDEO_LIST => self::getContentType(self::CONTENT_VIDEO_LIST)
		);
	}
	public function getCategoryRecommendType($type)
	{
		switch ($type){
			case self::CATEGORY_RECOMMEND_CANCEL:
				return Yii::t('category',"CANCEL");
				break;
			case self::CATEGORY_RECOMMEND_CHANNELS:
				return Yii::t('category',"CHANNEL");
				break;
			case self::CATEGORY_RECOMMEND_SITE:
				return Yii::t('category',"HOME");
				break;
		}
	}
	
	public function generateCategoryRecommendDropdownListArray()
	{
		return array(
			self::CATEGORY_RECOMMEND_CANCEL=>self::getCategoryRecommendType(self::CATEGORY_RECOMMEND_CANCEL),
			self::CATEGORY_RECOMMEND_CHANNELS=>self::getCategoryRecommendType(self::CATEGORY_RECOMMEND_CHANNELS),
			self::CATEGORY_RECOMMEND_SITE=>self::getCategoryRecommendType(self::CATEGORY_RECOMMEND_SITE)
		);
	}
	
	public function getCategoryModelByType($type)
	{
		$models = Category::model()->findAll(array(
			'condition'=>'cate_type = :cate_type',
			'order'=>'cate_type ASC, cate_pid DESC, cate_id ASC',
			'params'=>array(':cate_type'=>$type),
		));
		return $models;
	}
	
	//获取相关类型的分类名称
	public function getMenuByType($type)
	{
		$model = self::getCategoryModelByType($type);
		
		$result = array();
		$i = 0;
		foreach($model as $data){
			$result[$i]['id'] = $data->cate_id;
			$result[$i]['pid'] = $data->cate_pid;
			$result[$i]['cate_name'] = $data->cate_name;
		
			$i++;
		}
		
		return $result;
	}
	
	public function getCategoryDeepZeroInfo($categoryType = Category::CATEGORY_NEWS)
	{
		$all = Category::model()->getCategoryModuleList($categoryType);
		$flip = array_flip($all);
		
		$need = array_shift($all);
		
		return array(
			'id'=>$flip[$need],
			'value'=>$need
		);
		
	}
	
	public function getCategoryModuleList($type)
	{
		$list = array();
	
		$models = self::getCategoryModelByType($type);
	
		if($models == null)
		{
			//			$list = array(
			//				0=>'无'
			//			);
			$list = array(0=>'无');
		}
		else
		{
			$items = self::getChildrenObject($models);
			foreach ($items as $item)
			{
				$nbsp = "";
				for($i=1;$i<$item->deep;$i++){
					$nbsp .= "--";
				}
				$list[$item->cate_id]=$nbsp.$item->cate_name;
			}
				
		}
	
		return $list;
	
	}
	
	public function getCategoryDropdownList($type)
	{
		$list = array();

		$models = self::getCategoryModelByType($type);
		
		if($models == null)
		{
//			$list = array(
//				0=>'无'
//			);
			$list = array(0=>'无');
		}
		else
		{
			$items = self::getChildrenObject($models);
			foreach ($items as $item)
			{
				$nbsp = "";
				for($i=1;$i<$item->deep;$i++){
					$nbsp .= "--";
				}
				$list[$item->cate_id]=$nbsp.$item->cate_name.'['.self::getContentType($item->cate_contype).']';
			}	
					
		}
		
		return $list;		
		
	}
	
	public function ArticleCategoryId()
	{
		return array(
			Category::CATEGORY_BASEINFO,
			Category::CATEGORY_NEWS,
			Category::CATEGORY_DEYUE,
			Category::CATEGORY_JIAOWU,
			Category::CATEGORY_PARENTS,
			Category::CATEGORY_PARTY,
			Category::CATEGORY_STUDENTS,
			Category::CATEGORY_TEACHER,
			Category::CATEGORY_ABOUT,
			Category::CATEGORY_CUSTOMER,
			Category::CATEGORY_MEDIA
		);
	}
	
	//学校网站新增，显示所有文章相关分类
	
	public function getArticleCategoryDropdownList()
	{
		
		$i = 0;
		
		$dropdownlist = $list = array();
		
		$models = Category::model()->findAll(array(
			'order'=>'cate_order DESC, cate_id ASC'
		));
		
		foreach ($models as $model)
		{
			$list[] = $model->attributes;
		}
		
		
		
		$rows = self::model()->getChildrenArray($list);
		
		foreach ($rows as $row)
		{
			$nbsp = "";
			for($j=1;$j<$row['deep'];$j++){
				$nbsp .= "--";
			}
			
			$dropdownlist[$row['cate_id']] = $nbsp.$row['cate_name'].'  ['.self::model()->getContentType($row['cate_contype']).']';
			
		}
		
// 		UtilTools::dump($dropdownlist2);
		
		
		
// 		foreach ($this->ArticleCategoryId() as $id)
// 		{
// 			$arr = Category::model()->getCategoryDropdownList($id);
// 			$dropdownlist = array_merge($dropdownlist,$arr);
			
// 			$dropdownlist = UArray::arrayMerge($dropdownlist, $arr);
			
// 		}
		
//		$news = Category::model()->getCategoryDropdownList(Category::CATEGORY_NEWS);
//		$party = Category::model()->getCategoryDropdownList(Category::CATEGORY_PARTY);
//		$base = Category::model()->getCategoryDropdownList(Category::CATEGORY_BASEINFO);
//		$deyue = Category::model()->getCategoryDropdownList(Category::CATEGORY_DEYUE);
//		$jiaowu = Category::model()->getCategoryDropdownList(Category::CATEGORY_JIAOWU);
//		$parent_campus = Category::model()->getCategoryDropdownList(Category::CATEGORY_PARENTS);
//		$student = Category::model()->getCategoryDropdownList(Category::CATEGORY_STUDENTS);
//		$teacher = Category::model()->getCategoryDropdownList(Category::CATEGORY_TEACHER);
//		$about = Category::model()->getCategoryDropdownList(Category::CATEGORY_ABOUT);
//		
//		$dropdownlist = array_merge($base,$news,$party,$deyue,$jiaowu,$parent_campus,$student,$teacher,$about);
		
		return $dropdownlist;
	}
	
	public function getCategoryImage($id, $action = 'file', $htmlOptions=array('width'=>'120'),$folder = 1)
	{
		$cateimg = Yii::app()->params['uploadCategoryPath'].self::getCategoryName($id).'_thumb.jpg';
		if(!file_exists(".$cateimg")){
			$cateimg = Yii::app()->params['actionIco']['path'].$folder.'/'.$action.'.png';
		}
		return CHtml::image($cateimg,$action,$htmlOptions);
	}
	
	
	/**
	 * @method findParent($id,&$catename="")
	 * @todo Generate the categoryIteratorName
	 * @param $id
	 * @param $catename
	 * 
	 * ************************************************************
	 * Notice:Input any param $id and output a number which may not exists
	 * *************************************************************
	 */
	protected  function findParent($id,&$catename=""){
		if(isset($id))	
		{
			$model=Category::model()->findbyPk($id);
			if(count($model)){
	//			echo count($model);
	//			die($model->count());
				if($model->cate_pid != 0)
				{				
					$catename = $model->cate_pid.$catename;
					self::findParent($model->cate_pid,$catename);
				}
				return $catename;
			}
			return 0;
		}
	}
	
	public static function findParentZero($id, &$category=array())
	{
		$model = Category::model()->findByPk($id);
		if($model)
		{
			$category[] = $model->cate_id;
			self::findParentZero($model->cate_pid, $category);
		}
		
		return $category;
	}
	
	public static function findParentArray($id,&$catename=array())
    {
		$model=Category::model()->findByPk($id);
		if(count($model)){
	//		echo count($model);
	//		die($model->count());
//			var_dump($model);
			$catename[$model->cate_name] = array('category',$model->cate_pid);
			self::findParentArray($model->cate_pid,$catename);			
		}
		return $catename;
	}
    
    public function getCateDeep($id,$type=Category::CATEGORY_NEWS)
    {
        $models = self::model()->findAll('cate_type = :cate_type',array(
            ':cate_type'=>$type
        ));
        
        $arr = array();
        
        foreach($models as $item)
        {
            $arr[] = $item->attributes;
        }
        
        $details = self::getChildrenArray($arr);
        
        foreach($details as $row)
        {
            if($row['cate_id'] == $id)
            {                
                return $row['deep'];
            }
        }

    }
	
	/**
	 * Get the category name
	 * @method getCategoryName($id)
	 * @return Return the result $id's parents as (parent_id)(child_id)
	 * @param $id
	 */
	public static function getCategoryName($id)
	{
		return self::findParent($id).$id;
	}	
	
	/**
	 * 
	 * To check whether the category is the last node
	 * @param int $pid
	 */
	public function isLastNode($pid)
	{
		$model = Category::model()->findAll('cate_pid = :cate_pid',array(':cate_pid'=>$pid));
		return $model;
	}
	
	/**
	 * 
	 * Enter description here ...
	 * @param int $id
	 * @param string $action
	 */
	public function getCateInfo($id,$action="category")
	{
		$model = Category::model()->findByPk($id);
		return array($model->cate_name=>array($action,'id'=>$model->cate_id));
	}
	
	/**
	 * 
	 * Generate the breadcrumbs
	 * @method generateBreadcrumbs();
	 * @param int $id
	 * @param string $action
	 * @param unknown_type $catename
	 */
	public function generateBreadcrumbs($id,$action='list',&$catename=array(),&$model=null){
		if(isset($id))
		{
			$model=Category::model()->findbyPk($id);
			if(count($model)){
	//			echo count($model);
	//			die($model->count());
				
				$data = Category::model()->findByPk($model->cate_pid);		
				$catename[$model->cate_name] = array($action, 'id'=>$model->cate_id, 'c'=>urlencode($model->cate_name), 'm'=>urlencode(self::model()->getCategoryType(self::CONTENT_GALLERY)));
				
				//以下为学校主题模板增加内容
				if($model->cate_pid == 0 && $model->cate_contype == Category::CONTENT_GALLERY)
					$catename[$model->cate_name] = array('/work');//,'id'=>$model->cate_id,'c'=>urlencode($model->cate_name), 'm'=>urlencode(self::model()->getCategoryType(self::CONTENT_GALLERY)));
				//以下为学校主题模板增加内容
				elseif($model->cate_pid == 0 && $model->cate_contype == Category::CONTENT_STORY)
					$catename[$model->cate_name] = array('/blog');//,'id'=>$model->cate_id,'c'=>urlencode($model->cate_name), 'm'=>urlencode(self::model()->getCategoryType(self::CONTENT_STORY)));
				elseif ($model->cate_contype == Category::CONTENT_PAGE)
				{
					$catename[$model->cate_name] = array('/blog/list','id'=>$model->cate_id,'m'=>self::model()->getCategoryType(self::CONTENT_STORY));
				}	
				
					
				self::generateBreadcrumbs($model->cate_pid,$action,$catename);

				return $catename;
			}
			return $catename;

		}
	}
	
	/**
	 * 
	 * Generate the page title, base the breadcrumb
	 * @param array $breadcrumb
	 */
	public function generatePageTitle($breadcrumb,$connectStr='-')
	{
		$pagetitle = "";
		foreach ($breadcrumb as $key => $value) {
			$pagetitle.=$key.$connectStr;			
		}
		return str_replace('0', $breadcrumb[0], $pagetitle);
	}
    
    
   	/**
	 * 根据Action来设置Accordion激活状态
	 * Enter description here ...
	 * @param unknown_type $action
	 */
	function activeAccordion($action){
		switch ($action){
			case 'default':
				return 0;
				break;
			case 'news':
				return 1;
				break;
			case 'info':
				return 1;
				break;
			case 'media':
				return 2;
				break;
			case 'comment':
				return 3;
				break;
			case 'email':
				return 4;
				break;
            case 'faq':
                return 5;
                break;
            case 'links':
            	return 6;
            	break;
            case 'skin':
            	return 7;
            	break;
			case 'tools':
				return 9;
				break;
			case 'user':
				return 8;
				break;
			default:
				return 0;
				break;
			}
	}    
	
	/**
	 * 以下为手机微博专门提供的分类,获取分类ID
	 */
	public function getMblogCategoryInfo()
	{
		$catename = '微博心语';
		$cateParent = Category::model()->getCategoryDeepZeroInfo(Category::CATEGORY_NEWS);
		
		$mblog = Category::model()->find(array(
				'condition'=>'cate_name = :cate_name AND cate_pid = :cate_pid',
				'params'=>array(
					':cate_name' => $catename,
					':cate_pid' => $cateParent['id']
				)
			)	
		);
		
		
		if ($mblog)
		{
			return $mblog;
		}
		else
		{
			$mblog = new Category();
			$mblog->cate_name = $catename;
			$mblog->cate_pid = $cateParent['id'];
			$mblog->cate_type = Category::CATEGORY_NEWS;
			$mblog->cate_contype = Category::CONTENT_STORY;
			$mblog->cate_order = 600;
			$mblog->cate_recommend = Category::CATEGORY_RECOMMEND_CANCEL;
			$mblog->cate_des = '微博心语--利用手机便可以轻松记录自己的心语。';
			
			if($mblog->save())
			{
				return $mblog;
			}
		}
		
	}
	


}